import {toast} from 'nc-lightapp-front';
import moment from 'moment';

export default class CardAction {
    constructor(comp) {
        this.comp = comp;
    }

    /**
     * @desc: 手动校验单据
     * @param {String} formCode  表单
     * @return:
     */
    checkBillBymanual = (formCode) => {
        const {form, myLeave} = this.comp.props;
        const {getFormItemsValue} = form;
        let begintime;
        let endtime;
        let length;
        let timeFlag = false;
        let lengthFlag = false;
        let minunit = getFormItemsValue(formCode, 'minunit').value
        begintime = getFormItemsValue(formCode, 'tripoffbegintime').value;
        endtime = getFormItemsValue(formCode, 'tripoffendtime').value;
        length = getFormItemsValue(formCode, 'tripoffday').value;
        if (begintime > endtime) {
            timeFlag = true
        }
        if (!length || !(length - 0)) {
            lengthFlag = true
        }
        if (timeFlag) {
            // 结束时间必须晚于开始时间！
            toast({
                color: 'danger',
                content: myLeave.json['6040-000011']
            })
            return false
        }
        if (timeFlag && lengthFlag) {
            toast({
                color: 'warning',
                content: myLeave.json['6040-000013']
            })
            return false
        }
        return true
    }

    // 销差切换显示
    revokeTripoffChoose(carCode, key, value) {
        const {dispatch, myLeave, form} = this.comp.props;
        const {
            getAllFormValue,
            setFormItemsRequired,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsValue,
            getFormItemsValue
        } = form;
        let target = {
            tripoffbegintime: false, // 开始时间
            tripoffendtime: false, // 结束时间
            tripoffday: false
        }
        if (value === '1') {
            let tripbegintime = getFormItemsValue(carCode, 'tripbegintime')
            let tripendtime = getFormItemsValue(carCode, 'tripendtime')
            setItemsVisible(carCode, target)
            setFormItemsValue(carCode, {
                tripoffbegintime: tripbegintime,
                tripoffendtime: tripendtime,
                tripoffday: {
                    value: 0,
                    dispaly: 0
                }
            })
        } else {
            target.tripoffbegintime = true, // 开始时间
                target.tripoffendtime = true, // 结束时间
                target.tripoffday = true
            setItemsVisible(carCode, target)
            setFormItemsValue(carCode, {
                tripoffendtime: {},
                tripoffbegintime: {},
                tripoffday: {}
            })

        }
    }

    /**
     * @desc: 表单的编辑后事件(变动后触发)  1. 选择类型后，相应的组件修改 2. 选择时间后，动态计算时长
     * @param {Comment} props
     * @param {String} moduleId  区域id
     * @param {String} key  操作的键
     * @param {String} value 当前值
     * @param {String} oldValue 旧值
     * @return:
     */
    onAfterEvent = (props, moduleId, key, value, oldValue) => {
        const {form, meta} = props;
        const {dispatch, myLeave} = this.comp.props;
        const {
            getAllFormValue,
            setFormItemsRequired,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsValue,
            getFormItemsValue
        } = form;
        let obj
        if (moduleId === 'tripoff_card') {
            if (!this.checkBillBymanual(moduleId)) {
                return false
            }
            obj = {
                tripday: {
                    display: null,
                    value: null
                }
            }
            if (['tripoffbegintime', 'tripoffendtime'].indexOf(key) !== -1 && value.value) {
                value.value = value.value.slice(0, -2) + '00'
                props.form.setFormItemsValue(moduleId, {
                    [key]: value
                })
                this.handelTripofftime(moduleId, key, value.value);
            }
            // 销差 未出差
            if (key == 'dr_flag') {
                this.revokeTripoffChoose(moduleId, key, value.value)
            }
        } else if (moduleId === 'trip_card') {
            obj = {
                // tripbegintime: {
                //     display: null,
                //     value: null
                // },
                // tripendtime: {
                //     display: null,
                //     value: null
                // },
                tripday: {
                    display: null,
                    value: null
                }
            }
            if (key === 'pk_attend_staff') {
                const {meta} = this.comp.props;
                let temp = meta.getMeta();
                temp[moduleId].items.forEach(item => {
                    if (item.attrcode === "triptypeid") {
                        item.queryCondition = function () {
                            return {
                                pk_attend_staff: value && value.refpk
                            }
                        }
                    }
                });
                meta.setMeta(temp);
                obj['triptypeid'] = {
                    display: null,
                    value: null
                }
                this.clearTypeRelData(moduleId, obj);
                this.setDateDisabled(moduleId, true);
            } else if (key === 'triptypeid') {
                if (!value.value) {
                    this.clearTypeRelData(moduleId, obj);
                    this.setDateDisabled(moduleId, true);
                    return
                }
                this.setDateDisabled(moduleId, false);
                this.clearTypeRelData(moduleId, obj);
                this.handelTriptime(moduleId, 'tripbegintime')
            } else if (['tripbegintime', 'tripendtime'].indexOf(key) !== -1 && value.value) {

                value.value = value.value.slice(0, -2) + '00'
                props.form.setFormItemsValue(moduleId, {
                    [key]: value
                })

                this.handelTriptime(moduleId, key, value.value);
            }

        }
        obj = null
    }

    /**
     * @desc: 触发后端的编辑后事件处理相关的业务
     * @param {type}
     * @return:
     */
    editAction = (cardCode, key, callbackFn) => {
        const {dispatch, myLeave, form, meta: metas, formCode} = this.comp.props;
        const {
            getAllFormValue,
            setFormItemsRequired,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsValue,
            getFormItemsValue
        } = form;
        let model = getAllFormValue(cardCode)
        let formValue = model.rows[0].values
        // 提交表单时删除休假额度
        dispatch({
            type: 'myLeave/afterEditCard',
            payload: {
                formData: {
                    model
                },
                attrCode: key
            }
        }).then(res => {
            if (myLeave.feedStatus) {
                res.data.valueMap.leaveoffday = model.rows[0].values.breastfeedingleaveday
            }
            if (res.data.valueMap) {
                setFormItemsValue(cardCode, res.data.valueMap)
            }
            if (res.data.itemMetaMap) {
                Object.keys(res.data.itemMetaMap).forEach(key => {
                    if (key === 'disabled') {
                        setFormItemsDisabled(cardCode, res.data.itemMetaMap[key])
                    } else if (key === 'required') {
                        setFormItemsRequired(cardCode, res.data.itemMetaMap[key])
                    } else if (key === 'visible') {
                        setItemsVisible(cardCode, res.data.itemMetaMap[key])
                    }
                })
            }
            if (res.data.extend) {
                // let keys = Object.keys(res.data.extend);
                if (res.data.extend['minTime']) {
                    let minTime = res.data.extend['minTime'];
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            minTime
                        }
                    })
                    let minunit = getFormItemsValue(cardCode, 'minunit').value
                    this.handleDateFormControl(cardCode, minTime, minunit)
                }
                if (cardCode === 'overtime_card' && res.data.extend['durationObject']) {
                    let durationObject = res.data.extend['durationObject']
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            durationObject
                        }
                    })
                }
                if (res.data.extend['startTime'] && res.data.extend['endTime']) {
                    if (cardCode === 'tripoff_card') {
                        setFormItemsValue(cardCode, {
                            tripoffbegintime: {
                                value: res.data.extend['startTime']
                            },
                            tripoffendtime: {
                                value: res.data.extend['endTime']
                            }
                        })
                    } else {
                        setFormItemsValue(cardCode, {
                            begintime: {
                                value: res.data.extend['startTime']
                            },
                            endtime: {
                                value: res.data.extend['endTime']
                            }
                        })
                    }
                }
                if (res.data.extend['isattachment']) {
                    // todo   附件上传是否必须
                    let isattachment = res.data.extend['isattachment']
                    let excessLength = res.data.extend['attachmentExcessDay'] || res.data.extend['attachmentExcessHour'] || '0'
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            isattachment,
                            excessLength
                        }
                    })
                }
            }
            if (typeof (callbackFn) === 'function') {
                callbackFn()
            }
        })
    }
    /**
     * @desc: 类型变更后手动清除时间 变更相关元数据的设置
     * @param {type}
     * @return:
     */
    clearTypeRelData = (cardCode, valueMap) => {
        const {dispatch, myLeave, form} = this.comp.props;
        const {
            getAllFormValue,
            setFormItemsRequired,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsValue,
            getFormItemsValue
        } = form;
        setFormItemsValue(cardCode, valueMap)
    }
    /**
     * @desc:
     * @param {type} minTime 1 0.5  2 1
     * @param {type} minunit 1 小时  2 天
     * @return:
     */
    handleDateFormControl = (cardCode, minTime, minunit) => {
        const {dispatch, myLeave, form, meta} = this.comp.props;
        const {setFormItemsRequired, setItemsVisible, setFormItemsValue} = form;
        let target = {
            begintime: true, // 开始时间
            endtime: true, // 结束时间
            showbegindate: true, // 开始日期
            showenddate: true, // 结束日期
            start_day_type: true, // 开始 上午下午
            end_day_type: true   // 结束 上午下午
        }
        setFormItemsValue(cardCode, {
            'breastfeedingleaveday': {},
            'breastfeedingleaveway': {}
        });
        if (myLeave.feedStatus) {
            // 1天
            target.begintime = false;
            target.endtime = false;
            target.start_day_type = false;
            target.end_day_type = false;
            setItemsVisible(cardCode, target);
            setFormItemsRequired(cardCode, target);
        } else if (minunit === '1') {
            // 小时
            target.showbegindate = false;
            target.showenddate = false;
            target.start_day_type = false;
            target.end_day_type = false;
            setItemsVisible(cardCode, target);
            setFormItemsRequired(cardCode, target);
        } else if (minunit === '2') {
            if (minTime === '1') {
                // 半天
                target.begintime = false;
                target.endtime = false;
                setItemsVisible(cardCode, target);
                setFormItemsRequired(cardCode, target);

                setFormItemsValue(cardCode, {
                    'breastfeedingleaveday': {
                        value: '1'
                    },
                    'breastfeedingleaveway': {
                        value: '1'
                    }
                });
            } else if (minTime === '2') {
                // 1天
                target.begintime = false;
                target.endtime = false;
                target.start_day_type = false;
                target.end_day_type = false;
                setItemsVisible(cardCode, target);
                setFormItemsRequired(cardCode, target);
            }
        }
    }
    /**
     * @desc: 清空和选择休假类别后设置日期控件的disabled属性
     * @param {type}
     * @return:
     */
    setDateDisabled = (cardCode, disabled) => {
        const {dispatch, myLeave, form} = this.comp.props;
        const {setFormItemsDisabled} = form;
        let disabledMap = {};
        disabledMap = {
            tripbegintime: disabled, // 开始日期
            tripendtime: disabled // 结束日期
        }

        setFormItemsDisabled(cardCode, disabledMap)
        disabledMap = null
    }

    /**
     * @desc: 计算出可以填补单据的日期
     * @param {type}
     * @return: [Boolean]
     */
    isIncludeLimitDate = (limit, curDate) => {
        const {myLeave} = this.comp.props;
        limit = limit - 0
        if (limit === -1) {
            return false
        }
        let expectedDate = moment().subtract(limit, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
        if (curDate < expectedDate) {
            toast({
                color: 'warning',
                content: myLeave.json['6040-000036']
            })
            return true
        }
    }

    /**
     * @desc: 销差开始结束时间，校验及触发编辑后事件
     * @param {type}
     * @return:
     */
    handelTripofftime = (cardCode, key, value) => {
        const {dispatch, myLeave, form} = this.comp.props;
        const {
            getAllFormValue,
            setFormItemsRequired,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsValue,
            getFormItemsValue
        } = form;
        let falg = true;
        if (!getFormItemsValue(cardCode, 'tripoffendtime').value) {
            falg = false;
        }
        if (!getFormItemsValue(cardCode, 'tripoffbegintime').value) {
            falg = false;
        }
        if (falg) {
            this.editAction(cardCode, 'tripoffendtime');
        }
    }
    /**
     * @desc: 请假时间补充 时 分 秒  半天或者天假别 都会用到begintime、endtime 字段去计算时长，需要把时间copy到begintime字段上
     *        上午 统一添加 08:00:00 下午 统一添加 20:00:00
     *        整天的统一为 00:00:00  date类型控件选到的为当前时间精确到秒~~~
     * @param  value {String} 当前时间
     * @param  type {Number} 替换的类型 0 '00:00:00' 1 '08:00:00' 2 '20:00:00' 3 '23:59:59'
     * @return: 替换后的时间
     */
    fillDateTime = (value, type) => {
        const timeArr = ['00:00:00', '08:00:00', '20:00:00', '23:59:59'];
        let arr = value.split(' ');
        arr.splice(1, 1, timeArr[type])
        return arr.join(' ')
    }

    /**
     * @desc: 出差开始结束时间，校验及触发编辑后事件
     * @param {type}
     * @return:
     */
    handelTriptime = (cardCode, key, value) => {
        const {dispatch, myLeave, form} = this.comp.props;
        const {
            getAllFormValue,
            setFormItemsRequired,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsValue,
            getFormItemsValue
        } = form;
        let falg = true;
        if (!getFormItemsValue(cardCode, 'tripendtime').value) {
            falg = false;
        }
        if (!getFormItemsValue(cardCode, 'tripbegintime').value) {
            falg = false;
        }
        let type = getFormItemsValue(cardCode, 'triptypeid').value;
        if (!type) {
            falg = false
        }
        if (falg) {
            this.editAction(cardCode, 'tripbegintime');
        }
    }

    onBeforeEvent = () => {
        return true
    }

}
